<template>
  <div class="base-select-condition-container">
    <div class="condition-item-group" v-for="(condition, index) in conditions" :key="condition._key">
      <div class="condition-item">
        <div class="condition-item-title">
          <div class="title-name">{{$t('zhongqi.setting.conditionGroup')}}{{(index + 1)}}</div>
          <div class="close" v-if="(conditions.length !== 1)" @click="removeItem(index)">
            <i class="el-icon-close"></i>
          </div>
        </div>
        <div class="condition-item-detail" v-for="(ele, ind) in condition.subCondition" :key="ind">
          <div class="first-select">
            <!-- 选择模块 -->
            <el-cascader
              :options="optionsList"
              v-model="ele.module"
              @change="update($event, ele, index)"
            ></el-cascader>
          </div>
          <!-- 选择字段 -->
          <ConditionSearchItem 
            :fields="ele.fieldsOptions"
            :condition-item="ele.conditionItem"
            :is-show-init-value="true"
            :is-clear-value="true"
            :module="module"
            :condition-module="ele.module[0]"
            @selectFiledChange="selectFiledChange($event, ele, index)"
            @changeValue="changeValue"
          />
          <div class="condition-item-detail-operators">
            <el-button
              class="del-icon"
              icon="iconfont icon-delete"
              :disabled="disabledDeleteBtn(condition.subCondition)"
              @click="removeItemDetail(index, ind)"
            ></el-button>
          </div>
          
        </div>
        <div class="add-item-detail" @click="addItemDetail(index)">
          + {{$t('zhongqi.setting.andConditions')}}
        </div>
      </div>
      <div class="split-text" v-if="(index !== conditions.length -1)">{{$t('zhongqi.setting.orText')}}</div>
    </div>
    <div class="condition-button-wrap">
      <el-button v-if="(conditions.length > 0)" type="primary" @click="addItem()">+ {{$t('zhongqi.setting.orConditions')}}</el-button>
      <el-button v-else type="primary" @click="addItem()">+ {{ $t('zhongqi.setting.addConditions') }}</el-button>
    </div>
  </div>
</template>

<script>
import ConditionSearchItem from '@src/component/AdvancedSearch/ConditionSearchItem.vue'
import { t } from '@src/locales';
import _ from 'lodash';

export default {
  name: 'base-select-condition',
  props: {
    optionsList: {
      type: Array,
      default: () => []
    },
    optionMaps: {
      type: Object,
      default: () => ({}),
    },
    defaultModule: {
      type: Array,
      default: () => []
    },
    defaultConditionItem: {
      type: Object,
      default: null,
    },
    value: {
      type: Array,
      default: () => []
    },
    max: {
      type: [String, Number],
      default: ''
    },
    module: {
      type: String,
      default: ''
    },
  },
  data() {
    return {
      conditions: [],
    }
  },
  computed: {
    
  },
  watch: {
    value: {
      immediate: true,
      deep: true,
      handler(newValue) {
        this.conditions = _.cloneDeep(newValue)
      }
    }
  },
  mounted() {
    if (this.conditions.length == 0) {
      // 第一次加载时使用默认条件
      this.addItem(true)
    }
  },
  methods: {
    async update(val, item, index, originFields) {
      // 选择了第二级触发事件
      if (val.length == 2) {
        this.$emit('cascaderChange', val[1], item, index)
      }
      this.$set(item, 'originFieldsOptions', originFields ?? this.optionMaps[val[0]])
      this.$set(item, 'fieldsOptions', this.optionMaps[val[0]])
      this.clearConditionSearchItem(item.conditionItem)
    },
    selectFiledChange(val, item, index) {
      if (!val.formId) return;
      this.conditions.forEach((condition, ind) => {
        // 选中字段后，同一条件组的其它条件的字段数据需要重新处理
        if (index == ind) {
          // 当前条件组已选择的字段数据
          let fieldArr = []
          condition.subCondition.forEach(item => {
            const field = item.conditionItem?.field || {}
            fieldArr.push(field)
          })
          condition.subCondition.forEach(item => {
            const field = item.conditionItem?.field || {}
            if (val.formId == field.formId && val.fieldName != field.fieldName) {
              const arr = fieldArr.filter(f => f.fieldName != field.fieldName)
              // 过滤掉其它条件已选择的字段
              item.fieldsOptions = item.originFieldsOptions.filter(f => {
                let hasExist = false
                arr.forEach(_f => {
                  if (f.formId == _f.formId && f.fieldName == _f.fieldName) {
                    hasExist = true
                  }
                })
                return !hasExist
              })
            }
          })
        }
      })
    },
    changeValue() {
      this.$emit('changeValue')
    },
    // 判断是否不可删除按钮
    disabledDeleteBtn(subCondition) {
      return subCondition.length === 1 && this.conditions.length === 1
    },
    // 切换清空数据
    clearConditionSearchItem (data) {
      this.$set(data, 'comp', '');
      this.$set(data, 'field', null);
      this.$set(data, 'operator', '');
      this.$set(data, 'fieldName', '');
      this.$set(data, 'value', null)
    },
    // 添加或条件
    addItem(useDefaultConditionItem) {
      if (!this.validateMaxCondition()) return
      // 添加条件组
      const conditionItem = {
        fieldName: '', //  子模块的fieldName
        operator: '', // 操作符
        value: [], // 选中的结果值
        comp: '', // 条件的控件类型
        field: null
      }
      const defaultConditionItem = this.defaultConditionItem || conditionItem
      this.conditions.push({
        subCondition: [
          {
            module: this.defaultModule, // 模块 客户/产品/合同
            conditionItem: useDefaultConditionItem ? defaultConditionItem : conditionItem,
            fieldsOptions: this.optionMaps[this.defaultModule[0]]
          }
        ],
        _key: Math.random()
      })
    },
    // 添加且条件
    addItemDetail(index) {
      this.conditions[index].subCondition.push(
        {
          module: this.defaultModule, // 模块 客户/产品/合同
          conditionItem: {
            fieldName: '', //  子模块的fieldName
            operator: '', // 操作符
            value: [], // 选中的结果值
            comp: '', // 条件的控件类型
            field: null
          },
          fieldsOptions: this.optionMaps[this.defaultModule[0]]
        },
      )
    },
    validateMaxCondition() {
      if (this.max) {
        const length = this.conditions.length
        if (length >= this.max) {
          this.$platform.alert(t('common.base.tip.choiceLimit', {limit: this.max}))
          return false
        }
        return true
      }
      return true
    },

    // 删除条件组
    removeItem(index) {
      this.conditions.splice(index, 1)
      this.$emit('removeItem')
    },

    removeItemDetail(index, itemIndex) {
      if (this.conditions[index].subCondition.length === 1) {
        // 条件组内只有一个条件的话，点击删除，就删除整个条件组
        this.conditions.splice(index, 1)
      } else {
        this.conditions[index].subCondition.splice(itemIndex, 1)
      }
    },
  },
  components: {
    ConditionSearchItem
  },
}
</script>

<style lang="scss">
.base-select-condition-container {
  .condition-item-group {
    .condition-item {
      padding: 12px 16px;
      background: #F5F5F5;
      margin: 12px 0;
      .condition-item-title {
        display: flex;
        justify-content: space-between;
        margin-bottom: 8px;
        .title-name {
          font-size: 14px;
          color: #262626;
          font-weight: bold;
          line-height: 20px;
        }
        .close {
          cursor: pointer;
        }
      }
      .condition-item-detail {
        display: flex;
        align-items: center;
        margin-bottom: 12px;
        .condition-search-item__condition-select .el-select {
          width: 140px;
        }
        .first-select {
          width:160px;
          margin-right: 12px;
        }
        .condition-item-detail-operators {
          text-align: center;
          .del-icon {
            width: auto;
            padding: 0;
            background: transparent;
            border: none;
            font-size: 16px;
            border-radius: 0;
            margin-left: 14px;
            margin-top: 8px;
            &:hover {
              color: #d9363e;
            }
          }
        }
        .biz-form-remote-select {
          background: #fff;
        }
      }

      .add-item-detail {
        width: 60px;
        color: $color-primary-light-6;
        font-size: 14px;
        font-weight: 400;
        margin-top: 12px;
        cursor: pointer;
      }
    }
    .split-text {
      width: 14px;
      height: 20px;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #595959;
      line-height: 20px;
    }
  }
}
</style>